package com.intellagric.agriecom.service.agriecom_produce_category;

import com.github.pagehelper.PageHelper;
import com.intellagric.agriecom.module.agriecom_produce_category.AgriecomProduceCategoryService;
import com.intellagric.common.pojo.LayuiDataGridResult;
import com.intellagric.common.pojo.ResponseMessage;

import com.intellagric.dao.agriecom.agriecom_produce_category.AgriecomProduceCategoryDao;
import com.intellagric.mapper.AgriecomProduceCategoryMapper;
import com.intellagric.pojo.AgriecomProduceCategory;
import com.intellagric.pojo.AgriecomProduceCategoryExample;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;



@Service
public class AgriecomProduceCategoryServiceImpl implements AgriecomProduceCategoryService {

    @Autowired
    private AgriecomProduceCategoryMapper produceCategoryMapper;
    @Autowired
    private AgriecomProduceCategoryDao agriecomProduceCategoryDao;

    @Override
    public ResponseMessage addProduceCategory(AgriecomProduceCategory produceCategory) {

        produceCategory.setCreateDate(new Date(System.currentTimeMillis()));
        //当选择0分类时，getProduceCategoryById这个方法就那不到数据，getLevel()就会抛空指针
//        produceCategory.setLevel(this.getProduceCategoryById(produceCategory.getParentId()).getLevel()+1);
        produceCategory.setId(UUID.randomUUID().toString().replaceAll("-",""));

        if(produceCategoryMapper.insertSelective(produceCategory)==1)
            return ResponseMessage.success();
        else
            return ResponseMessage.fail();

    }

    @Override
    public ResponseMessage deleteProduceCategory(String id) {

        if(produceCategoryMapper.deleteByPrimaryKey(id)==1)
            return ResponseMessage.success();
        else
            return ResponseMessage.fail();
    }

    @Override
    public ResponseMessage editProduceCategory(AgriecomProduceCategory quotation) {

            quotation.setUpdateDate(new Date(System.currentTimeMillis()));
        if(produceCategoryMapper.updateByPrimaryKeySelective(quotation)==1)
            return ResponseMessage.success();
        else
            return ResponseMessage.fail();
    }

    @Override
    public AgriecomProduceCategory getProduceCategoryById(String id) {
        return produceCategoryMapper.selectByPrimaryKey(id);
    }

    @Override
    public LayuiDataGridResult getProduceCategoryList() {
        AgriecomProduceCategoryExample produceCategoryExample=new AgriecomProduceCategoryExample();
        produceCategoryExample.createCriteria().andIdIsNotNull();
        produceCategoryExample.setOrderByClause("sort asc");
        List<AgriecomProduceCategory> agriecomProduceCategoryList = produceCategoryMapper.selectByExample(produceCategoryExample);
        LayuiDataGridResult result = new LayuiDataGridResult();
        result.setData(agriecomProduceCategoryList);
        return result;
    }


    @Override
    public LayuiDataGridResult getProduceCategoryList(int page, int rows) {
        PageHelper.startPage(page,rows);


        return getProduceCategoryList();
    }


    /**
     * 查询菜单数据信息，生成树形菜单
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getMenu() {
        //查询所有列表数据
        LayuiDataGridResult result = new LayuiDataGridResult();
        List<AgriecomProduceCategory> agriecomProduceCategoryList = this.getProduceCategoryList().getData();
        result.setData(agriecomProduceCategoryList);

        //查询顶级菜单
        List<AgriecomProduceCategory> rootCategoryList = this.getCategoryByParentId("0").getData();

        //生成树形菜单数据，为一级菜单设置子菜单，getChild是递归调用的
        for (AgriecomProduceCategory agriecomProduceCategory : rootCategoryList) {
            agriecomProduceCategory.setChildren(getChild(agriecomProduceCategory.getId(), agriecomProduceCategoryList));
        }
        result.setData(rootCategoryList);
        return result;
    }

    private List<AgriecomProduceCategory> getChild(String id, List<AgriecomProduceCategory> agriecomProduceCategoryList) {
        // 子菜单
        List<AgriecomProduceCategory> childList = new ArrayList<>();

        // 遍历所有节点，将父菜单id与传过来的id比较
        for (AgriecomProduceCategory agriecomProduceCategory : agriecomProduceCategoryList) {
            if (agriecomProduceCategory.getParentId() != null) {   //所有非以及菜单的都要加入chidList中（递归）
                if (agriecomProduceCategory.getParentId().equals(id)) {
                    childList.add(agriecomProduceCategory);
                }
            }
        }

        // 把子菜单的子菜单再循环一遍
        for (AgriecomProduceCategory agriecomProduceCategory : childList) {// 没有url子菜单还有子菜单（暂不考虑url的问题）
            // 递归
            agriecomProduceCategory.setChildren(getChild(agriecomProduceCategory.getId(), agriecomProduceCategoryList));
        }
        //这里应该放在for上面把？？？？？？？？？??????????????????????????????????
        // 递归退出条件
        if (childList.size() == 0) {
            return null;
        }
        return childList;
    }

    /**
     * 异步查询菜单，通过父id查询
     * @Param parentId
     * @return LayuiDataGridResult
     */
    @Override
    public LayuiDataGridResult getCategoryByParentId(String parentId) {
        AgriecomProduceCategoryExample produceCategoryExample=new AgriecomProduceCategoryExample();

        produceCategoryExample.setOrderByClause("sort asc");
        produceCategoryExample.createCriteria().andParentIdEqualTo(parentId);
        List<AgriecomProduceCategory> rootAgriecomProduceCategoryList = produceCategoryMapper.selectByExample(produceCategoryExample);
        LayuiDataGridResult result = new LayuiDataGridResult();
        result.setData(rootAgriecomProduceCategoryList);
        return result;

    }

    @Override
    public ResponseMessage batchDeleteProduceCategory (String[] ids) {


        if (agriecomProduceCategoryDao.batchDeleteByPrimaryKey(ids) <1)
            return ResponseMessage.fail();
        return ResponseMessage.success();
    }

    @Override
    public List<AgriecomProduceCategory> getCategoryChildren(String parentCategroyId) {
        AgriecomProduceCategoryExample example=new AgriecomProduceCategoryExample();
        example.createCriteria().andParentIdEqualTo(parentCategroyId);
        return produceCategoryMapper.selectByExample(example);
    }

    @Override
    public AgriecomProduceCategory getAncestorNode(String categoryId,int level) {
        AgriecomProduceCategory produceCategory=this.getProduceCategoryById(categoryId);
        if(produceCategory!=null) {
            if (produceCategory.getLevel() == level)
                return produceCategory;
            else
                return this.getAncestorNode(produceCategory.getParentId(), level);
        }
        return null;

    }


}
